<template>
  <div class="image-uploader">
    <input type="file" ref="fileInput" @change="handleFileSelect" class="input-file">
    <label for="fileInput" @click="fileInput?.click">
      <el-avatar :src="imageUrl" alt="Preview" fit="contain" aria-placeholder="点击选择头像" />
    </label>
  </div>
</template>

<script lang="ts" setup>
import { ref, toRef, watch } from "vue"

const props = defineProps({
  imageUrl: {
    type: String,
    default: ""
  },
  file: {
    type: File,
    requare: false,
    default: undefined
  }
})
const imageUrlRef = toRef(props, "imageUrl");

// watch(imageUrlRef, (newValue, oldValue) => {
//   console.log("新值" + newValue);
//   console.log("旧值" + oldValue);
// })

// 事件提交
const emit = defineEmits(["update:imageUrl", "update:file"]);
// 文件选择框
const fileInput = ref<HTMLElement | null>(null);

const handleFileSelect = (e: Event) => {
  const target = e.target as HTMLInputElement;
  if (target.files && target.files.length > 0) {
    const selectFile = target.files[0];
    if (selectFile) {
      emit("update:file", selectFile);
      emit("update:imageUrl", URL.createObjectURL(selectFile));
    }
  }
}
</script>

<style scoped>
.image-uploader {
  position: relative;
  width: 200px;
}

.input-file {
  display: none;
}

.upload-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px dashed #ccc;
  border-radius: 4px;
  padding: 16px;
  cursor: pointer;
}

.upload-placeholder i {
  font-size: 24px;
  margin-bottom: 8px;
}
</style>
